package de.nak.fireDepartment.administrationAction;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.struts.ActionSupport;

import de.nak.fireDepartment.actionForms.DepartmentForm;
import de.nak.fireDepartment.model.Department;
import de.nak.fireDepartment.service.DepartmentService;
import de.nak.fireDepartment.service.LoginService;

/**
 * Action that shows the list of departments
 * 
 * @author Sven Redelin
 */
public class ShowDepartmentListAction extends ActionSupport {

	/**
	 * This method list all departments
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// Get the service
		WebApplicationContext ctx = getWebApplicationContext();
		DepartmentService departmentService = (DepartmentService)ctx.getBean("departmentService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// get all departments
		Collection<Department> departments = departmentService.listDepartments();
		// Store value in form
		DepartmentForm departmentListForm = (DepartmentForm) form;
		departmentListForm.setDepartments(departments);
		departmentListForm.setErrorCode("");
		// Return result
		return mapping.findForward("success");
	}
}
